package com.example.shortvideobackend.controller;

import com.example.shortvideobackend.dto.VideoRequest;
import com.example.shortvideobackend.entity.Video;
import com.example.shortvideobackend.service.VideoService;
import com.example.shortvideobackend.entity.Comment;
import com.example.shortvideobackend.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/videos")
@CrossOrigin(origins = "*")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private CommentService commentService;

    // 视频存储路径
    private static final String VIDEO_UPLOAD_DIR = "uploads/videos/";
    private static final String THUMBNAIL_UPLOAD_DIR = "uploads/thumbnails/";

    @PostMapping("/upload")
    public ResponseEntity<?> uploadVideo(@RequestParam("video") MultipartFile video,
                                       @RequestParam("thumbnail") MultipartFile thumbnail,
                                       @RequestParam("title") String title,
                                       @RequestParam("description") String description,
                                       @RequestParam("userId") Long userId) {
        try {
            // 创建上传目录
            Path videoUploadDir = Paths.get(VIDEO_UPLOAD_DIR);
            Path thumbnailUploadDir = Paths.get(THUMBNAIL_UPLOAD_DIR);
            
            if (!Files.exists(videoUploadDir)) {
                Files.createDirectories(videoUploadDir);
            }
            if (!Files.exists(thumbnailUploadDir)) {
                Files.createDirectories(thumbnailUploadDir);
            }

            // 生成唯一文件名
            String videoOriginalFilename = video.getOriginalFilename();
            String videoExtension = videoOriginalFilename != null ? 
                videoOriginalFilename.substring(videoOriginalFilename.lastIndexOf(".")) : ".mp4";
            String videoFilename = UUID.randomUUID().toString() + videoExtension;
            
            String thumbnailOriginalFilename = thumbnail.getOriginalFilename();
            String thumbnailExtension = thumbnailOriginalFilename != null ? 
                thumbnailOriginalFilename.substring(thumbnailOriginalFilename.lastIndexOf(".")) : ".jpg";
            String thumbnailFilename = UUID.randomUUID().toString() + thumbnailExtension;
            
            // 保存文件
            Path videoFilePath = videoUploadDir.resolve(videoFilename);
            Path thumbnailFilePath = thumbnailUploadDir.resolve(thumbnailFilename);
            
            Files.copy(video.getInputStream(), videoFilePath);
            Files.copy(thumbnail.getInputStream(), thumbnailFilePath);
            
            // 生成文件URL
            String videoUrl = "/uploads/videos/" + videoFilename;
            String thumbnailUrl = "/uploads/thumbnails/" + thumbnailFilename;
            
            // 创建视频记录
            Video createdVideo = videoService.createVideo(title, description, videoUrl, thumbnailUrl, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", createdVideo);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping
    public ResponseEntity<?> createVideo(@RequestBody VideoRequest request) {
        try {
            Video video = videoService.createVideo(
                    request.getTitle(),
                    request.getDescription(),
                    request.getVideoUrl(),
                    request.getThumbnail(),
                    request.getUserId()
            );
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", video);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping
    public ResponseEntity<?> getAllVideos() {
        try {
            List<Video> videos = videoService.getAllVideos();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getVideoById(@PathVariable Long id) {
        try {
            Video video = videoService.getVideoById(id);
            videoService.incrementViews(id);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", video);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getVideosByUserId(@PathVariable Long userId) {
        try {
            List<Video> videos = videoService.getVideosByUserId(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 点赞/取消点赞视频
    @PostMapping("/{videoId}/like")
    public ResponseEntity<?> toggleLike(@PathVariable Long videoId, @RequestParam Long userId) {
        try {
            Video updatedVideo = videoService.toggleLike(videoId, userId);
            boolean isLiked = videoService.isLikedByUser(videoId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", updatedVideo);
            response.put("isLiked", isLiked);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 检查用户是否已点赞视频
    @GetMapping("/{videoId}/like/check")
    public ResponseEntity<?> checkLikeStatus(@PathVariable Long videoId, @RequestParam Long userId) {
        try {
            boolean isLiked = videoService.isLikedByUser(videoId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("isLiked", isLiked);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 添加评论
    @PostMapping("/{videoId}/comments")
    public ResponseEntity<?> addComment(@PathVariable Long videoId, 
                                      @RequestParam Long userId, 
                                      @RequestParam String content) {
        try {
            Comment comment = commentService.addComment(videoId, userId, content);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", comment);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取视频评论
    @GetMapping("/{videoId}/comments")
    public ResponseEntity<?> getComments(@PathVariable Long videoId) {
        try {
            List<Comment> comments = commentService.getCommentsByVideoId(videoId);
            long commentCount = commentService.getCommentCountForVideo(videoId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", comments);
            response.put("count", commentCount);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除评论
    @DeleteMapping("/comments/{commentId}")
    public ResponseEntity<?> deleteComment(@PathVariable Long commentId, @RequestParam Long userId) {
        try {
            commentService.deleteComment(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "评论删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}